<template>
  <div class="panel data-charts">
    <h2 class="panel-title">
      <TrendCharts class="el-icon" />
      历史数据
    </h2>
    <div class="charts-container">
      <!-- 时间范围选择器 -->
      <div class="chart-controls">
        <div class="time-range">
          <div 
            v-for="range in timeRanges" 
            :key="range.value"
            :class="['range-item', { active: currentTimeRange === range.value }]"
            @click="changeTimeRange(range.value)"
          >
            {{ range.label }}
          </div>
        </div>
      </div>
      
      <!-- 数据类型选择器 -->
      <div class="chart-tabs">
        <div 
          v-for="(tab, index) in tabs" 
          :key="index"
          :class="['tab-item', { active: currentTab === index }]"
          @click="changeTab(index)"
        >
          {{ tab.label }}
        </div>
      </div>
      
      <!-- 图表容器 -->
      <div class="chart" ref="chartRef"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { TrendCharts } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

const chartRef = ref(null)
const currentTab = ref(0)
const currentTimeRange = ref('day')
let chart = null

// 时间范围选项
const timeRanges = [
  { label: '日', value: 'day' },
  { label: '月', value: 'month' },
  { label: '年', value: 'year' }
]

// 数据类型选项
const tabs = [
  { label: '空气温度', type: 'airtemperature', unit: '°C' },
  { label: '土壤湿度', type: 'soilmoisture', unit: '%' },
  { label: '土壤温度', type: 'soiltemperature', unit: '°C' },
  { label: '土壤氮含量', type: 'soilnitrogen', unit: 'mg/kg' },
  { label: '二氧化碳', type: 'carbondioxide', unit: 'ppm' }
]

// 生成模拟数据
const generateMockData = (range) => {
  const now = new Date()
  const data = []
  
  switch (range) {
    case 'day':
      // 生成24小时的数据
      for (let i = 0; i < 24; i++) {
        const time = new Date(now)
        time.setHours(time.getHours() - i)
        data.unshift({
          time: time.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
          value: Math.random() * 30 + 20 // 生成20-50之间的随机数
        })
      }
      break
      
    case 'month':
      // 生成30天的数据
      for (let i = 0; i < 30; i++) {
        const time = new Date(now)
        time.setDate(time.getDate() - i)
        data.unshift({
          time: `${time.getMonth() + 1}/${time.getDate()}`,
          value: Math.random() * 30 + 20
        })
      }
      break
      
    case 'year':
      // 生成12个月的数据
      for (let i = 0; i < 12; i++) {
        const time = new Date(now)
        time.setMonth(time.getMonth() - i)
        data.unshift({
          time: `${time.getMonth() + 1}月`,
          value: Math.random() * 30 + 20
        })
      }
      break
  }
  
  return data
}

// 更新图表
const updateChart = (data, tabInfo) => {
  const option = {
    title: {
      text: tabInfo.label,
      textStyle: { 
        color: '#fff',
        fontSize: 14
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const param = params[0]
        return `${param.name}<br/>${param.seriesName}: ${param.value}${tabInfo.unit}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.time),
      axisLabel: {
        color: '#fff',
        rotate: currentTimeRange.value === 'year' ? 0 : 45
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        color: '#fff',
        formatter: value => `${value}${tabInfo.unit}`
      }
    },
    series: [{
      name: tabInfo.label,
      type: 'line',
      smooth: true,
      data: data.map(item => item.value),
      areaStyle: {
        opacity: 0.1
      },
      itemStyle: {
        color: '#42b983'
      }
    }]
  }
  
  chart.setOption(option)
}

// 切换时间范围
const changeTimeRange = (range) => {
  currentTimeRange.value = range
  const data = generateMockData(range)
  updateChart(data, tabs[currentTab.value])
}

// 切换数据类型
const changeTab = (index) => {
  currentTab.value = index
  const data = generateMockData(currentTimeRange.value)
  updateChart(data, tabs[index])
}

// 组件挂载时初始化
onMounted(() => {
  chart = echarts.init(chartRef.value)
  const data = generateMockData('day')
  updateChart(data, tabs[0])
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => chart?.resize())
})

// 监听标签变化，重新调整图表大小
watch(currentTab, () => {
  chart?.resize()
})
</script>

<style scoped>
.data-charts {
  height: 400px;
}

.charts-container {
  height: calc(100% - 50px);
  padding: 15px;
}

.chart-controls {
  margin-bottom: 15px;
}

.time-range {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.range-item {
  padding: 5px 15px;
  border-radius: 4px;
  cursor: pointer;
  color: #888;
  background: rgba(255, 255, 255, 0.1);
  transition: all 0.3s;
}

.range-item:hover {
  color: #42b983;
}

.range-item.active {
  background: #42b983;
  color: #fff;
}

.chart-tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.tab-item {
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
  color: #888;
  transition: all 0.3s;
}

.tab-item:hover {
  color: #42b983;
}

.tab-item.active {
  background: #42b983;
  color: #fff;
}

.chart {
  height: calc(100% - 90px);
}
</style> 